package net.wanho.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.RequiredArgsConstructor;
import net.wanho.constant.CaptchaConstant;
import net.wanho.constant.UserConstant;
import net.wanho.dto.LoginUserDTO;
import net.wanho.mapper.UserInfoMapper;
import net.wanho.po.UserInfo;
import net.wanho.service.LoginService;
import net.wanho.util.CurrentUtil;
import net.wanho.util.JwtUtil;
import net.wanho.vo.LoginUserVo;
import net.wanho.vo.R;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
    private final RedisTemplate redisTemplate;
    private final UserInfoMapper userInfoMapper;
    @Override
    public Map<String, String> captchaImage() {
        //生成验证码
        Captcha captcha=new SpecCaptcha();
        // 生成uuid
        String uuid= UUID.randomUUID().toString();

        //将验证码保存到redis中
        redisTemplate.opsForValue().set(CaptchaConstant.CAPTCHA_PREFIX+uuid,captcha.text(),CaptchaConstant.CAPTCHA_EXPIRE, TimeUnit.MINUTES);
        //返回验证码和uuid
        Map<String,String> map=new HashMap<>();
        map.put("uuid",uuid);
        map.put("img",captcha.toBase64());
        return map;
    }

    @Override
    public String login(LoginUserDTO loginUserDTO) {
        /**
         * 判断验证码
         */
        String key=CaptchaConstant.CAPTCHA_PREFIX+loginUserDTO.getUuid();
        String trueCode= (String) redisTemplate.opsForValue().get(key);
        if(ObjectUtil.isEmpty(trueCode)){
           throw new RuntimeException("验证码已过期");
        }
        //删除验证码
        redisTemplate.delete(key);
        if(!trueCode.equalsIgnoreCase(loginUserDTO.getCode())){
            throw new RuntimeException("验证码错误");
        }

        /**
         * 判断用户
         */
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(UserInfo::getUserCode,loginUserDTO.getUserCode());
        lambdaQueryWrapper.eq(UserInfo::getUserPwd, SecureUtil.md5(loginUserDTO.getUserPwd()));
        UserInfo userInfo =userInfoMapper.selectOne(lambdaQueryWrapper);
        if (ObjectUtil.isEmpty(userInfo)){
            throw new RuntimeException("用户不存在");
        }
        if(userInfo.getUserState().equals(UserConstant.USER_STATE_DISABLE)){
            throw new RuntimeException("用户已禁用");
        }
        /**
         * 生成token
         */
        Map<String,Object> payload=new HashMap<>();
        payload.put("userId",userInfo.getUserId());
        payload.put("userCode",userInfo.getUserCode());
        payload.put("userName",userInfo.getUserName());
        payload.put("userType",userInfo.getUserType());
        String token="Bearer "+JwtUtil.generate(payload);

        return token;



    }

    @Override
    public LoginUserVo getCurrentUser() {
        Integer userId=CurrentUtil.getUserId();
        UserInfo userInfo=userInfoMapper.selectById(userId);
        LoginUserVo loginUserVo=new LoginUserVo();
        BeanUtils.copyProperties(userInfo,loginUserVo);
        return loginUserVo;
    }
}
